﻿using System.Net.NetworkInformation;
using System.ServiceProcess;
using Citi.Helpers;
using Citi.SecurityHelper;

namespace Citi.Scheduler.Domain
{
    public class MachineService
    {
        public Machine Machine { get; set; }
        public string ServiceName { get; set; }
        public User Responsible { get; set; }
        private string Domain { get; set; }
        private string NetworkUser { get; set; }
        private string NetworkPassword { get; set; }
        private const int TimeoutMilliseconds = 30000;
        private readonly string fullDomain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        private string Hostname
        {
            get
            {
                return Machine.FullName.EndsWith(fullDomain) ? Machine.HostName : Machine.FullName;
            }
        }

        public MachineService(Machine machine, string service, string domain, string networkUser, string networkPassword)
        {
            Machine = machine;
            ServiceName = service;
            Responsible = machine.User;
            Domain = domain;
            NetworkUser = networkUser;
            NetworkPassword = networkPassword;
        }

        public ServiceControllerStatus GetServiceStatus()
        {
            //using (GetImpersonateUser())
            using (ImpersonateCitiUser.GetImpersonateUser(NetworkUser, NetworkUser, NetworkPassword))
                return WindowsUtil.GetServiceStatus(ServiceName, Hostname, TimeoutMilliseconds);
        }

        public void StartService()
        {
            using (ImpersonateCitiUser.GetImpersonateUser(NetworkUser, NetworkUser, NetworkPassword))
            //using (GetImpersonateUser())
                WindowsUtil.StartService(ServiceName, Hostname, TimeoutMilliseconds);
        }

        //private ImpersonateUser GetImpersonateUser()
        //{
        //    var impersonate = new ImpersonateUser();

        //    if (!string.IsNullOrWhiteSpace(Domain) && !string.IsNullOrWhiteSpace(NetworkUser) && !string.IsNullOrWhiteSpace(NetworkPassword))
        //        impersonate.Impersonate(Domain, NetworkUser, NetworkPassword);

        //    return impersonate;
        //}
    }
}
